package zhao.ben.quan.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import zhao.ben.quan.constant.MessageConstant;
import zhao.ben.quan.constant.RedisMessageConstant;
import zhao.ben.quan.entity.Result;
import zhao.ben.quan.pojo.Member;
import zhao.ben.quan.service.MemberService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController//@controller+@respustbody
@RequestMapping("member")//映射地址
public class MemberController {
    
    @Autowired//注入redis连接池
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/login")
    public Result login(HttpServletResponse resp, @RequestBody Map map){
        //从前台拿到用户输入手机号和验证码
        String telephone = (String) map.get("telephone");//手机号
        String validateCode = (String) map.get("validateCode");//验证码

        //从redis中获取验证码,进行对比
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        if(validateCode!=null && validateCodeInRedis!=null && validateCode.equals(validateCodeInRedis)){
            //验证码对比成功
            //判断当前用户是否为会员
            Member member = memberService.findBytelephone(telephone);//根据用户手机号去会员表中查询
            if(member==null){
                member = new Member();
                //注入用户输入的值
                member.setPhoneNumber(telephone);//手机号
                member.setRegTime(new Date());//注册时间

                //如果不是会员,就注册
                memberService.add(member);
            }
            //向客户端浏览器写入cookie,内容为手机号
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60*60*24*30);//有效期30天
            resp.addCookie(cookie);//响应到浏览器

            //保存会员信息到redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,300,json);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);//登陆成功
        }
        //验证码输入错误
        return new Result(false, MessageConstant.VALIDATECODE_ERROR);
    }
}
